<?php


namespace App\Functions;

use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Intervention\Image\Facades\Image;

class UploadFile
{
    const RAW = 'raw';
    const EXT = 'jpg';
    const ROOT_DIR = '/upload';

    public static function  save(UploadedFile $file, $save_dir = '/upload/archive')
    {
        ini_set ('memory_limit', '400M'); 
        //mkdir
        $root_dir = public_path(self::ROOT_DIR);
        if ( ! file_exists($root_dir)) mkdir($root_dir);

        $path = $file->getRealPath();
        $img = Image::make($path);

        $abs_dir = public_path($save_dir);
        if ( ! file_exists($abs_dir)) mkdir($abs_dir);

        $save_dir .= '/'.md5_file($path);

        //这里判断是否需要讲图片转为jpg格式，只要为了兼容之前在前端页面上加的.jpg的硬编码
        $abs_dir = public_path($save_dir) . '/' . self::RAW;

        // 如果以文件MD5命名的文件夹已经存在，则不重复储存文件
        if (!file_exists(public_path($save_dir)) && mkdir(public_path($save_dir))) {
            $img->save($abs_dir);
        }
        
        $img->save($abs_dir . '.' . self::EXT);
        return $save_dir;
    }

    public function read(Request $request, $uri, $size)
    {
        ini_set ('memory_limit', '400M');

        if ($size == 'raw') {
            return preg_match('/.jpe?g/', $request->url()) ? redirect(asset("$uri/$size")) : redirect(asset("$uri/$size").'.jpg');
        }

        $sizes = explode('_', $size);
        if (count($sizes) == 1) {
            $sizes = explode('x', $size);
        } else if (count($sizes) == 3) {
            $xy = explode('x', $sizes[1]);
            $width = $sizes[2];
            $sizes = explode('x', $sizes[0]);
        } else if (count($sizes) == 4) {
            $rotate = $sizes[3];
            $xy = explode('x', $sizes[1]);
            $width = $sizes[2];
            $sizes = explode('x', $sizes[0]);
        }else {
            abort(404);
        }

        $path = public_path($uri);
        if (!file_exists($path)) abort(404);

        // try {
            $raw = public_path($uri) . "/" . self::RAW;

            $ext = preg_match('/.jpe?g/', $request->url())
                ? ('.' . (file_exists($raw . '.jpeg') ? 'jpeg' : self::EXT))
                : '';
            
            if (!file_exists($raw)) {
                $raw = $raw . '.' . self::EXT;
            }

            $img = Image::make($raw);

            if(isset($rotate)) {
                $img->rotate(-(int)$rotate);
            }

            if (isset($xy)) {
                $width = $width > ($img->width() * 2) ? $img->width() * 2 : $width;
                $img->crop($sizes[0], $sizes[1], $xy[0], $xy[1]);
                $img->widen((int)$width);
            } else {
                $width = (int)$sizes[0];
                $height = isset($sizes[1]) ? (int)$sizes[1] : 0;

                $width = $width > ($img->width() * 2) ? $img->width() * 2 : $width;
                $height = $height > ($img->height() * 2) ? $img->height() * 2 : $height;

                if ($height == 0) {
                    //等比例缩放
                    $img->widen($width);
                } elseif ($width == 0) {
                    $img->heighten($height);
                } else {
                    $img->fit($width, $height);
                }
            }
            $img->save("{$uri}/{$size}" . $ext);

            return redirect(asset("$uri/$size" . $ext));

    }
}